import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.font_manager as fm
import warnings
warnings.filterwarnings('ignore')

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False

# 下载苹果公司(AAPL)近一年的数据
print("正在下载AAPL数据...")
data = yf.download("AAPL", period="1y", progress=False)

# 检查数据是否成功下载
if data.empty:
    print("错误：无法下载数据，请检查网络连接或股票代码")
    exit()

print(f"成功下载 {len(data)} 条数据")
print(f"数据时间范围：{data.index[0].strftime('%Y-%m-%d')} 到 {data.index[-1].strftime('%Y-%m-%d')}")

# 计算短期和长期移动平均线
data['MA5'] = data['Close'].rolling(window=5, min_periods=1).mean()   # 5日均线
data['MA10'] = data['Close'].rolling(window=10, min_periods=1).mean() # 10日均线
data['MA50'] = data['Close'].rolling(window=50, min_periods=1).mean() # 50日均线（长期参考）

# 创建图表
fig, ax = plt.subplots(figsize=(14, 8))

# 绘制收盘价和均线
ax.plot(data.index, data['Close'], label='收盘价', color='#1f77b4', linewidth=2, alpha=0.8)
ax.plot(data.index, data['MA5'], label='MA5 (5日均线)', color='#ff7f0e', linewidth=1.5)
ax.plot(data.index, data['MA10'], label='MA10 (10日均线)', color='#2ca02c', linewidth=1.5)
ax.plot(data.index, data['MA50'], label='MA50 (50日均线)', color='#d62728', linewidth=2)

# 设置图表属性
ax.set_title("AAPL 移动平均线分析", fontsize=16, fontweight='bold', pad=20)
ax.set_xlabel("日期", fontsize=12)
ax.set_ylabel("价格 (USD)", fontsize=12)
ax.legend(loc='upper left', fontsize=10)
ax.grid(True, alpha=0.3)

# 优化x轴日期显示
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=2))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))

# 旋转x轴标签以便更好地显示
plt.setp(ax.xaxis.get_majorticklabels(), rotation=45, ha='right')

# 调整布局
plt.tight_layout()

# 显示图表
plt.show()

# 打印当前价格和均线信息
latest_data = data.iloc[-1]
print(f"\n最新数据 ({data.index[-1].strftime('%Y-%m-%d')}):")
print(f"收盘价: ${float(latest_data['Close']):.2f}")
print(f"MA5: ${float(latest_data['MA5']):.2f}")
print(f"MA10: ${float(latest_data['MA10']):.2f}")
print(f"MA50: ${float(latest_data['MA50']):.2f}")

# 简单的技术分析
close_price = float(latest_data['Close'])
ma5 = float(latest_data['MA5'])
ma10 = float(latest_data['MA10'])
ma50 = float(latest_data['MA50'])

if ma5 > ma10 > ma50:
    print("技术分析: 短期趋势向上 (多头排列)")
elif ma5 < ma10 < ma50:
    print("技术分析: 短期趋势向下 (空头排列)")
else:
    print("技术分析: 趋势不明确")